#pragma once
#include "../log/log.h"
#include <chrono>
#include <vector>
namespace Log
{
    void bench(const std::string &name, size_t thread_num, size_t msg_count, size_t msg_len)
    {
        // 1.获取日志器
        Log::Logger::ptr lg = getlLogger(name);
        if (lg.get() == nullptr)
        {
            return;
        }
        // 2. 组织指定长度的日志消息
        std::string msg(msg_len, 'M');
        // 3. 创造指定个数线程
        std::vector<std::thread> threads;
        std::cout << "输入线程数量: " << thread_num << "  输出日志数量: " << msg_count << "  输出总日志大小: " << msg_len * msg_count / 1024 / 1024 << "MB" << std::endl;
        std::vector<double> cost_time(thread_num);            // 该vector 保存每个线程的耗时 时间
        size_t msg_count_per_thread = msg_count / thread_num; // 每个线程要写日志的个数

        for (int i = 0; i < thread_num; i++)
        {
            // emplace_back直接在 vector 内部构造这个线程对象，更高效，无额外 move 构造；
            threads.emplace_back([&, i]()
                                 {
                // 4. 线程函数内部开始计时
                
                auto start = std::chrono::high_resolution_clock::now();
                // 5. 循坏写日志
                for(size_t j = 0; j < msg_count_per_thread; j++)
                {
                    lg->fatal("%s",msg.c_str());
                }
                // 6. 线程函数结束计时    
                auto end = std::chrono::high_resolution_clock::now();
                auto cost = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
                cost_time[i] = cost.count();
                auto avg = msg_count_per_thread / cost_time[i];
                std::cout << "线程" << i  << " 耗时：" << cost.count() << "s" << std::endl; });
        }
        for (auto &thr : threads)
        {
            thr.join();
        }
        // 7. 计算总耗时
        double max_cost = 0;
        for (auto cost : cost_time)
        {
            max_cost = (max_cost < cost ? cost : max_cost);
        }
        std::cout << "总消耗时间: " << max_cost << "s" << std::endl;
        std::cout << "平均每秒输出: " << (size_t)(msg_count / max_cost) << "条日志" << std::endl;
        std::cout << "平均每秒输出: " << (size_t)(msg_len * msg_count / max_cost / 1024/ 1024) << "MB" << std::endl;
    }
}
